package golf.stockdata.framework.spring;


import golf.stockdata.framework.exception.ApplicationException;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationObjectContainer {
	
	private static Logger logger = Logger.getLogger(ApplicationObjectContainer.class);
	
	protected boolean inUsed = false;
	private String containerUniqueID;
	
	private HashMap<String, Object> abilities = new HashMap<String, Object>();
	
	private BeanFactory BEAN_FACTORY = null;
	
	public ApplicationObjectContainer(String ID){
		logger.debug(">>> ApplicationObjectContainer");
		
		containerUniqueID = ID;
		
		logger.debug("Initializing Spring Context for container:" + containerUniqueID);
		BEAN_FACTORY = new ClassPathXmlApplicationContext("spring-config.xml");
		logger.debug("<<< ApplicationObjectContainer");
	}
	
	public Object getAbility(String abilityName){
		
		logger.debug(">>> getAbility");
		
		Object ability = abilities.get(abilityName);
		
		if(inUsed){
			if(ability == null){
				
				ability = BEAN_FACTORY.getBean(abilityName);
				if(ability == null){
					throw new ApplicationException("Error loading ability:".concat(abilityName));
				}else{
					abilities.put(abilityName, ability);
				}
			}
		}else{
			logger.error("Getting ability from an arbitary AOC is not allowed");
			throw new ApplicationException("Getting ability from an arbitary AOC is not allowed");
		}
		
		logger.debug("<<< getAbility");
		return ability;
	}
	
	public void cleanUpAbilities(){
		logger.debug(">>> cleanUpAbilities");
		abilities.clear();
		logger.debug("<<< cleanUpAbilities");
	}
	
	public void release(){
		logger.debug(">>> release");
		inUsed = false;
		logger.debug("AOC:" + containerUniqueID + " is now free");
		logger.debug("<<< release");
	}

}
